const jwt = require('jsonwebtoken');

// const fs = require('fs');

const { JWT_TOKEN_KEY, JWT_TOKEN_EXPIRESIN } = require('./settings');

// TODO：key值
// const Key = fs.readFileSync('../../public/key/').toString();

// 创建token
exports.createToken = (id, username) => {
  return jwt.sign({ id, username }, JWT_TOKEN_KEY, {
    expiresIn: JWT_TOKEN_EXPIRESIN, // 设置过期时间
    algorithm: 'RS256', // 采用加密算法
  });
};

// 获取token
exports.checkToken = async (ctx, next) => {
  // 获取token
  const authorization = ctx.headers.authorization;
  if (!authorization) {
    ctx.body = {
      code: 3001,
      msg: '未授权',
      result: null,
    };
    return;
  }

  let token;
  if (/^Bearer /.test(authorization)) {
    token = authorization.replace('Bearer ', '');
  } else {
    ctx.body = {
      code: 3001,
      msg: '无效token,请重新登录!',
      result: null,
    };
    return;
  }

  // 验证token
  let res;
  try {
    res = jwt.verify(token, '???');
  } catch (err) {
    ctx.body = {
      code: 3001,
      msg: '无效token,请重新登录!',
      result: null,
    };
    return;
  }
  ctx.user = res;
  await next();
};
